<template>
  <div
    class="add-equment-card-container"
    :class="(disabled || simple) && 'disabled'"
  >
    <div class="title" v-if="fieldSource.length > 0">
      <div class="text">{{ title }}</div>
      <div class="del-button" @click="deleteHandle()" v-if="isShowDelete">
        删除
      </div>
    </div>
    <div class="equment-card-content" v-if="fieldSource.length > 0">
      <a-row>
        <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules">
          <span v-for="item in fields" :key="item.id">
            <!-- input -->
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="12"
              :xl="12"
              :xxl="6"
              v-if="item.fieldType == 'input'"
            >
              <a-form-model-item
                :label="
                  item.fieldName +
                  `${item.fieldUnit ? '(' + item.fieldUnit + ')' : ''}`
                "
                :prop="item.equFieldCode"
                :rules="[
                  {
                    required: item.fieldRequired == 1,
                    message: item.placeHolder || '请输入' + item.fieldName,
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <a-input
                  :disabled="disabled || item.isEditable == 1"
                  allowClear
                  v-model="ruleForm[item.equFieldCode]"
                  :type="item.fieldContentType"
                  :maxLength="Number(item.maxLength) || 200"
                  :placeholder="item.placeHolder || '请输入' + item.fieldName"
                />
              </a-form-model-item>
            </a-col>

            <!-- 日期选择 -->
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="12"
              :xl="12"
              :xxl="6"
              v-if="item.fieldType == 'date'"
            >
              <a-form-model-item
                ref="phyEquipmentNumber"
                :label="item.fieldName"
                :prop="item.equFieldCode"
                :rules="[
                  {
                    required: item.fieldRequired == 1,
                    message: item.placeHolder || '请选择' + item.fieldName,
                    trigger: ['change'],
                  },
                ]"
              >
                <a-date-picker
                  :disabled="disabled || item.isEditable == 1"
                  v-model="ruleForm[item.equFieldCode]"
                  valueFormat="YYYY-MM-DD"
                  type="date"
                  :placeholder="item.placeHolder || '请选择' + item.fieldName"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>

            <!-- select -->
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="12"
              :xl="12"
              :xxl="6"
              v-if="item.fieldType == 'select'"
            >
              <a-form-model-item
                ref="phyEquipmentNumber"
                :label="item.fieldName"
                :prop="item.equFieldCode"
                :rules="[
                  {
                    required: item.fieldRequired == 1,
                    message: item.placeHolder || '请选择' + item.fieldName,
                    trigger: ['change'],
                  },
                ]"
              >
                <a-select
                  allowClear
                  :disabled="disabled || item.isEditable == 1"
                  v-model="ruleForm[item.equFieldCode]"
                  :placeholder="item.placeHolder || '请选择' + item.fieldName"
                >
                  <a-select-option
                    :value="select.value"
                    v-for="(select, index) in item.selectDataList"
                    :key="index"
                  >
                    {{ select.text }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>

            <a-col :span="24" v-if="item.fieldType == 'map'">
              <!-- 经度坐标 -->
              <a-col :span="12">
                <a-form-model-item
                  label="经纬度坐标"
                  prop="long"
                  ref="long"
                  class="long"
                >
                  <a-input
                    v-model="ruleForm.long"
                    :disabled="disabled || item.isEditable == 1"
                    ref="longEl"
                    placeholder="请输入经度"
                  />
                </a-form-model-item>
              </a-col>

              <!-- 纬度坐标 -->
              <a-col :span="12">
                <a-form-model-item
                  label=""
                  prop="lat"
                  ref="lat"
                  class="latitude"
                >
                  <a-input
                    :disabled="disabled || item.isEditable == 1"
                    v-model="ruleForm.lat"
                    placeholder="请输入纬度"
                    class="lat"
                    ref="latEl"
                  />
                  <a-button
                    type="primary"
                    @click="resetLocation()"
                    v-if="!disabled"
                  >
                    重置
                  </a-button>
                </a-form-model-item>
              </a-col>
            </a-col>

            <!-- 地图 -->
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="24"
              :xl="24"
              :xxl="24"
              v-if="item.fieldType == 'map'"
            >
              <div class="map-container">
                <div
                  class="map-condition"
                  v-if="!disabled || item.isEditable == 1"
                >
                  <a-radio-group v-model="mapSearchType">
                    <a-radio :value="0"> 按关键字 </a-radio>
                    <a-radio :value="1"> 按坐标 </a-radio>
                  </a-radio-group>
                  <div class="input-contaier flex">
                    <div class="fill-body">
                      <!-- 关键字 -->
                      <div class="by-keyword" v-if="mapSearchType == 0">
                        <a-input
                          placeholder="请输入关键字"
                          v-model="mapKeyword"
                        />
                      </div>
                      <!-- 坐标 -->
                      <div class="by-location flex" v-if="mapSearchType == 1">
                        <a-input placeholder="请输入经度" v-model="mapLong" />，
                        <a-input placeholder="请输入纬度" v-model="mapLat" />
                      </div>
                    </div>
                    <div class="search-button" @click="mapSearch()">
                      <a-icon
                        type="search"
                        :style="{
                          fontSize: '20px',
                          color: '#fff',
                        }"
                      />
                    </div>
                  </div>
                </div>
                <div class="map-dom" :id="'map-dom_' + id"></div>
              </div>
            </a-col>
          </span>
        </a-form-model>
      </a-row>
    </div>
  </div>
</template>

<script>
import { getProInitGeo } from "@/utils";
export default {
  name: "addEquCard",
  props: {
    title: {
      type: String,
      default: "",
    },

    id: {
      type: String,
      default: "",
    },

    //是否展示删除按钮
    isShowDelete: {
      type: Boolean,
      default: true,
    },

    fieldSource: {
      type: Array,
      default: () => {
        return [];
      },
    },

    disabled: {
      type: Boolean,
      default: false,
    },

    simple: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ruleForm: {
        //经度
        long: undefined,
        // 纬度
        lat: undefined,
      },
      rules: {
        phyEquipmentNumber: [
          {
            required: true,
            message: "请输入实体设备编号",
            trigger: ["blur", "change"],
          },
        ],
        snNumber: [
          {
            required: true,
            message: "请输入SN号",
            trigger: ["blur", "change"],
          },
        ],
        equName: [
          {
            required: true,
            message: "请输入设备名称",
            trigger: ["blur", "change"],
          },
        ],
        long: [
          {
            required: true,
            message: "请输入经度",
            trigger: ["blur", "change", "input"],
          },
        ],
        lat: [
          {
            required: true,
            message: "请输入纬度",
            trigger: ["blur", "change"],
          },
        ],
        date: [
          {
            required: true,
            message: "请输入设备名称",
            trigger: "change",
          },
        ],
      },
      mapInstance: undefined,
      mapSearchType: 0,
      //经度
      mapLong: undefined,
      //纬度
      mapLat: undefined,
      //关键字
      mapKeyword: undefined,
      fields: [],
    };
  },
  watch: {
    fieldSource: {
      handler(val) {
        this.fields = val || [];
        this.fields.forEach((v) => {
          this.$set(this.ruleForm, v.equFieldCode, v.defalutValue || undefined);
        });

        if (val && val.length > 0 && val.some((v) => v.fieldType == "map")) {
          //获取默认坐标值
          let { defalutValue } = val.find((v) => v.fieldType == "map") || {};
          if (defalutValue) {
            let geo = defalutValue.split(",");
            this.ruleForm.long = geo[0] || "";
            this.ruleForm.lat = geo[1] || "";
          }
          //加载地图
          this.$nextTick((_) => {
            this.initMap(defalutValue);
          });
        }
      },
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    //验证输入
    dataValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve({
              id: this.id,
              title: this.title,
              form: this.ruleForm,
            });
          } else {
            reject({
              id: this.id,
              title: this.title,
              form: this.ruleForm,
            });
            return false;
          }
        });
      });
    },

    //删除
    deleteHandle() {
      this.$emit("handleDelete", {
        id: this.id,
        data: this.ruleForm,
      });
    },

    //地图实例化
    initMap(initGeo = "") {
      this.mapInstance = new AMap.Map("map-dom_" + this.id, {
        zoom: 15,
        center: getProInitGeo(),
      });
      //监听地图加载完成
      initGeo &&
        this.mapInstance.on("complete", () => {
          this.drawMarker([this.ruleForm.long, this.ruleForm.lat]);
          this.mapInstance.setFitView();
        });
      //绑定点击事件
      this.mapInstance.on("click", (e) => {
        this.getLocationByClick(e);
      });
    },

    //地图搜索
    mapSearch() {
      let {
        mapKeyword = "",
        mapSearchType,
        mapInstance,
        mapLong = "",
        mapLat = "",
      } = this;
      let that = this;
      //校验规则
      let lngRules =
        /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,20})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,20}|180)$/;
      let latRules =
        /^(\-|\+)?([0-8]?\d{1}\.\d{0,20}|90\.0{0,20}|[0-8]?\d{1}|90)$/;
      //清楚所有覆盖物
      mapInstance.clearMap();
      switch (mapSearchType) {
        //按关键字搜索
        case 0:
          if (!mapKeyword.replace(/\s+/g, "") || !mapInstance) return;
          mapInstance.plugin(["AMap.PlaceSearch"], function () {
            var placeSearch = new AMap.PlaceSearch({
              city: "全国",
              citylimit: true,
              autoFitView: true,
            });
            placeSearch.search(mapKeyword, async function (status, result) {
              if (status == "complete") {
                if (result.poiList.pois.length == 0) {
                  return;
                }
                result.poiList.pois.forEach((v) => {
                  let { location, name } = v;
                  that.drawMarker([location?.lng, location?.lat], name);
                });
                mapInstance.setFitView();
              }
            });
          });
          break;

        //按坐标搜索
        case 1:
          if (!mapLong.trim() || !mapLat.trim()) {
            this.$message.warning("请输入经纬度坐标");
            return;
          }
          let lonRe = new RegExp(lngRules);
          let latRe = new RegExp(latRules);
          if (!lonRe.test(mapLong)) {
            return this.$message.warning("经度不符合规范");
          }
          if (!latRe.test(mapLat)) {
            return this.$message.warning("纬度不符合规范");
          }
          that.drawMarker([mapLong, mapLat], "");
          mapInstance.setFitView();
          break;

        default:
          break;
      }
      setTimeout((_) => {}, 1000);
    },

    //绘制marker
    drawMarker(position = [], name = "") {
      if (!Array.isArray(position) || position.length == 0) {
        return;
      }
      var marker = new AMap.Marker({
        position,
        icon: new AMap.Icon({
          image:
            "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          size: new AMap.Size(30, 38), //设置icon的大小
          imageSize: new AMap.Size(30, 38),
        }),

        anchor: "bottom-center",
        offset: new AMap.Pixel(0, 0),
      });
      marker.setMap(this.mapInstance);
      //编订点击事件
      marker.on("click", (e) => {
        this.getLocationByClick(e);
      });
    },

    //点击获取坐标
    getLocationByClick(e = {}) {
      if (this.disabled) {
        return;
      }
      let { lnglat } = e;
      this.ruleForm.long = lnglat?.lng;
      this.ruleForm.lat = lnglat?.lat;
      this.$refs.longEl[0].focus();
      this.$refs.longEl[0].blur();
      this.$refs.latEl[0].focus();
      this.$refs.latEl[0].blur();
    },

    //重置坐标
    resetLocation() {
      this.ruleForm.long = undefined;
      this.ruleForm.lat = undefined;
    },
  },
};
</script>

<style lang="less" scoped>
.add-equment-card-container {
  background: #fff;
  margin-bottom: 20px;
  &:not(.disabled):hover {
    .equment-card-content {
      background: #f6f9ff;
      border-color: #fff;
    }
  }
  .title {
    color: var(--primary-color);
    font-size: 16px;
    .flex();
    justify-content: space-between;
    margin-bottom: 10px;
    .text {
      .flex();
      align-items: center;
      &::before {
        content: "";
        display: inline-block;
        width: 8px;
        height: 8px;
        background: var(--primary-color);
        border-radius: 50%;
        margin-right: 10px;
      }
    }
    .del-button {
      font-size: 14px;
      cursor: pointer;
      color: var(--echart-pale-red);
    }
  }
  .equment-card-content {
    border: 1px dashed #e0e0e0;
    padding: 24px 50px 0 0;
    transition: 0.3s;
    .map-container {
      height: 400px;
      border-radius: 4px;
      border: 1px solid #d4d4d4;
      margin: 0 0 20px 160px;
      background: #fff;
      position: relative;
      overflow: hidden;
      .map-condition {
        position: absolute;
        width: 460px;
        height: 86px;
        background: #ffffff;
        box-shadow: 0px 2px 3px 0px rgba(93, 93, 93, 0.34);
        border-radius: 4px;
        top: 10px;
        left: 10px;
        z-index: 99;
        padding: 10px 16px;
        .input-contaier {
          margin-top: 10px;
          height: 30px;
          .fill-body {
            flex: 1;
            border: 1px solid #d4d7d8;
            border-right: none;
            border-radius: 4px 0px 0px 4px;
            overflow: hidden;
            .flex();
            align-items: center;
            .by-keyword,
            .by-location {
              height: 100%;
              width: 100%;
            }
            .ant-input {
              width: 100%;
              height: 100%;
              padding: 0 10px;
              border: none;
              background: none;
              border-radius: 0;
              box-shadow: none;
            }
            .by-location {
              .ant-input {
                flex: 1;
                flex-shrink: 0;
              }
            }
          }
          .search-button {
            width: 45px;
            height: 30px;
            border-radius: 0px 4px 4px 0px;
            background: rgb(49, 131, 255);
            border: 1px solid rgb(49, 131, 255);
            .flex();
            align-items: center;
            justify-content: center;
            cursor: pointer;
          }
        }
      }
      .map-dom {
        width: 100%;
        height: 100%;
      }
    }
    /deep/ .ant-form-item {
      .flex();
      &.latitude {
        .ant-form-item-children {
          .flex();
          margin: 0 0 0 10px;
          .ant-btn {
            margin-right: 10px;
            margin-left: 10px;
          }
        }
        .ant-form-explain {
          margin-left: 10px;
          margin-top: 2px;
        }
      }
      .ant-form-item-label {
        width: 160px;
        flex-shrink: 0;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        .ant-form-item-control {
          position: relative;
          .ant-form-item-children {
            display: flex;
            width: 100%;
            .ant-input-affix-wrapper {
              display: flex;
              width: 100%;
            }
          }
        }
        textarea {
          height: 80px;
        }
        .ant-calendar-picker {
          width: 100%;
        }
      }
      /deep/.ant-select {
        width: 100%;
      }
    }
  }
}
</style>
